package top.wshape1.demo1.websocket;

import jakarta.websocket.*;
import jakarta.websocket.server.ServerEndpoint;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

/**
 * @author Wshape1
 * @version 1.0
 * @description
 * @since 2024-01-24
 */

/*
    WebSocket连接的路由，如ws://127.0.0.1:8080/websocket
    支持路径参数，如/websocket/{id}
 */
//@Component    //使用此注解Spring将自动注册ServerEndpoint
@ServerEndpoint("/websocket")
public class WebSocketEndpoint {

    private static final Logger log = LoggerFactory.getLogger(WebSocketEndpoint.class);

    /*
        若有路径参数则使用 @PathParam 注解来获取变量
     */
    @OnOpen
    public void onOpen(Session session, EndpointConfig config) {
        log.info("WebSocket连接建立");
    }

    @OnClose
    public void onClose(Session session, CloseReason closeReason) {
        log.info("WebSocket连接关闭");
    }

    @OnError
    public void onError(Session session, Throwable throwable) {
        log.warn("WebSocket连接异常：" + throwable);
    }

    @OnMessage
    public void onMessage(String message, Session session) {
        log.info("WebSocket消息：" + message);
    }

}
